const { Service } = require('egg');

class ArticleService extends Service {
  async getArticle(page, pageSize) {
    const { app } = this;
    if (page && pageSize) {
      const articleList = await this.app.model.Article.findAll({
        offset: (page - 1) * pageSize, // 查询的起始位置
        limit: Number(pageSize), // 限制返回的数据量 转换成整数u传给数据库否则会报错
      });
      return articleList;
    }
    const articleList = await app.model.Article.findAll();
    return articleList;
  }
  async getArticleById(id) {
    const { app } = this;
    return app.model.Article.findOne({ where: { id } });
  }
  async addArticle(data) {
    const { app } = this;
    const addArticle = app.model.Article.create(data);
    return addArticle;
  }
  async updateArticle(id, data) {
    const { app } = this;
    const updateArticle = await app.model.Article.findOne({ where: { id } });
    if (updateArticle) {
      return await updateArticle.update(data);
    }
    return null;

  }
  async delArticle(id) {
    const { app } = this;
    const delArticle = await app.model.Article.findOne({ where: { id } });
    if (delArticle) {
      return await delArticle.destroy();
    }
    return null;

  }
}
module.exports = ArticleService;
